package com.linhngua.code.gwt.client;



import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.linhngua.code.gwt.client.data.shop.Item;
import com.linhngua.code.gwt.client.ui.ItemView;

public class ItemViewPage implements EntryPoint {
	private RemoteInvocationAsync remoteInvocationAsync = GWT
			.create(RemoteInvocation.class);
	static final String ID_PARAM = "id";

	private ItemView itemView;

	private boolean alreadyPrompt;

	private RootPanel rootPanel;

	@Override
	public void onModuleLoad() {
		rootPanel = RootPanel.get("itemView");
		String idString = Window.Location.getParameter(ID_PARAM);
		int id = Integer.MIN_VALUE;
		try {
			id = Integer.parseInt(idString);
		} catch (NumberFormatException ex) {
			Window.prompt("Not a number", idString);
		}

		if (id != Integer.MIN_VALUE) {
			remoteInvocationAsync.getItem(id, new AsyncCallback<Item>() {
				
				@Override
				public void onSuccess(Item item) {
					itemView = new ItemView(item);
					itemView.addStyleName("itemView");
					int top = 50;
					int left = (int) (Window.getClientWidth() * 0.15);
					rootPanel.add(itemView, left, top);
					
				}
				
				@Override
				public void onFailure(Throwable t) {
					
					
				}
			});
		}

		
		// handle error

		GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {

			public void onUncaughtException(Throwable t) {
				if (!alreadyPrompt) {
					StringBuilder builder = new StringBuilder();
					for (StackTraceElement e : t.getStackTrace()) {
						builder.append(e.toString());
					}

					Window.prompt("Error", builder.toString());
					alreadyPrompt = true;
				}

			}

		});

	}

}
